﻿<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta http-equiv="Pragma" content="no-cache"/>
    <meta http-equiv="cache-Control" content="no-cache"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
    <meta name="HandheldFriendly" content="true">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-touch-fullscreen" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="#6f744c">
    <meta name="applicable-device" content="pc,mobile">
    <meta name="format-detection" content="telephone=no">
    <link rel="stylesheet" type="text/css" href="/Content/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="/Content/css/common.css">
    <link rel="stylesheet" type="text/css" href="/Content/css/main.css">
    <title>对话</title>
</head>

<body>
<header class="js-head">
    <a class="js-head-back">
        <i class="js-icon icon-back"></i>
    </a>
    <div class="js-head-title">
        曾文珊
    </div>
</header>
<div class="south_wrap">
    <div class="south_content" style="padding: 10px 0;">
        <div class="labiim-chat">
            <div class="labiim-chat-main" style="height: 262px;">
                <ul>
                    <!--       <li class="labiim-chat-date">
                        <span>昨天&nbsp;&nbsp;下午4:20</span>
                    </li>
                    <li>
                        <div class="labiim-chat-user">
                            <img src="/content/images/head.png">
                        </div>
                        <div class="labiim-chat-text">嗨，你好！我是张学友你好！我是张学友你好！我是张学友你好！我是张学友</div>
                    </li>
                    <li class="labiim-chat-mine">
                        <div class="labiim-chat-user">
                            <img src="/content/images/head.png">
                        </div>
                        <div class="labiim-chat-text">嗨，你好！我是老师</div>
                    </li>-->
                </ul>
            </div>
            <!--labiim-chat-main END-->

            <div class="labiim-chat-footer">
                <div class="labiim-chat-tool">
                    <!--<span id="face">
                        <img src="/content/images/im/smile.png" style="width: 20px;" />
                    </span>
                    <span>
                        <img src="/content/images/im/mic.png" style="width: 15px;" />
                    </span>-->
                    <span>
                        <img src="/content/images/im/image.png" style="width: 25px;"/>
                    </span>
                    <!--<span>
                        <img src="/content/images/im/video.png" style="width: 25px;" />
                    </span>
                    <span>
                        <img src="/content/images/im/file.png" style="width: 15px;" />
                    </span>-->
                </div>
                <div class="labiim-chat-border">
                    <!--  <input type="text" name="" class="" id="chat-text" /> -->
                    <!--  <input type="text" name="" class="" id="chat-text" /> -->
                    <textarea id="chat-text" class="sendMessage msgedit"></textarea>
                    <input type="file" name="" style="display: none;">
                    <div class="labiim-chat-border-right">
                        <button class="send btn">发送</button>
                    </div>
                </div>
            </div><!--labiim-chat-footer END-->


            <div class="labiim-chat-face">
                <div id="" class="labiim-chat-content">
                    <ul class="labiim-clear labiim-chat-list"></ul>
                </div><!--labiim-chat-face END-->

            </div>
        </div><!--labiim-chat END-->
    </div><!--south_content END-->
</div><!--south_wrap END-->
</body>

<script type="text/javascript" src="/Content/js/jquery-2.1.1.js"></script>
<script type="text/javascript" src="/Content/js/layer/layer.js"></script>
<script type="text/javascript" src="/Content/js/emjionExport.js"></script>
<script type="text/javascript" src="/Content/js/sdk/webim.js"></script>
<script type="text/javascript" src="/Content/js/sdk/json2.js"></script>
<script type="text/javascript">
    //监听新消息事件

    var selToID = '@ViewBag.SelToID';
    var selType = webim.SESSION_TYPE.GROUP;

//newMsgList 为新消息数组，结构为[Msg]
    function onMsgNotify(newMsgList) {
        //console.warn(newMsgList);
        var sess, newMsg, selSess;
        //获取所有聊天会话
        var sessMap = webim.MsgStore.sessMap();

        for (var j in newMsgList) { //遍历新消息
            newMsg = newMsgList[j];

            if (newMsg.getSession().id() == selToID) { //为当前聊天对象的消息
                selSess = newMsg.getSession();
                //在聊天窗体中新增一条消息
                //console.warn(newMsg);
                addMsg(newMsg);
            }
        }

        if (selSess) {
            //消息已读上报，以及设置会话自动已读标记
            webim.setAutoRead(selSess, true, false);

        }

        for (var i in sessMap) {
            sess = sessMap[i];
            if (selToID != sess.id()) { //更新其他聊天对象的未读消息数
                //updateSessDiv(sess.type(), sess.id(), sess.unread());
            }
        }
    }

    var onConnNotify = function(resp) {
        var info;
        switch (resp.ErrorCode) {
        case webim.CONNECTION_STATUS.ON:
            webim.Log.warn('建立连接成功: ' + resp.ErrorInfo);
            break;
        case webim.CONNECTION_STATUS.OFF:
            info = '连接已断开，无法收到新消息，请检查下你的网络是否正常: ' + resp.ErrorInfo;
            alert(info);
            webim.Log.warn(info);
            break;
        case webim.CONNECTION_STATUS.RECONNECT:
            info = '连接状态恢复正常: ' + resp.ErrorInfo;
            alert(info);
            webim.Log.warn(info);
            break;
        default:
            webim.Log.error('未知连接状态: =' + resp.ErrorInfo);
            break;
        }
    };

    @*var loginInfo = {
        sdkAppID: 1400065236,
        appIDAt3rd: 1400065236,
        identifier: '@ViewBag.AccountID',
        identifierNick: "@ViewBag.AccountID",
        userSig: '@ViewBag.UserSig',
        accountType: 22208
    }*@

    //拉比测试
    var loginInfo = {
        sdkAppID: 1400071705,
        appIDAt3rd: 1400071705,
        identifier: '@ViewBag.AccountID',
        identifierNick: "@ViewBag.AccountID",
        userSig: '@ViewBag.UserSig',
        accountType: 22208
    }

    var listeners = {
        'onMsgNotify': onMsgNotify,
        "onConnNotify": onConnNotify, //监听连接状态回调变化事件,必填
        "onKickedEventCall": onKickedEventCall
    }

    //发送消息(文本或者表情)
    function onSendMsg() {

        //var selToID = "test2";
        //var selType = webim.SESSION_TYPE.C2C;
        var selSess;
        if (!selToID) {
            alert("你还没有选中好友或者群组，暂不能聊天");
            $("#send_msg_text").val('');
            return;
        }
        //获取消息内容
        var msgtosend = document.getElementsByClassName("msgedit")[0].value;
        var msgLen = webim.Tool.getStrBytes(msgtosend);

        if (msgtosend.length < 1) {
            alert("发送的消息不能为空!");
            $("#send_msg_text").val('');
            return;
        }
        var maxLen, errInfo;
        if (selType == webim.SESSION_TYPE.C2C) {
            maxLen = webim.MSG_MAX_LENGTH.C2C;
            errInfo = "消息长度超出限制(最多" + Math.round(maxLen / 3) + "汉字)";
        } else {
            maxLen = webim.MSG_MAX_LENGTH.GROUP;
            errInfo = "消息长度超出限制(最多" + Math.round(maxLen / 3) + "汉字)";
        }
        if (msgLen > maxLen) {
            alert(errInfo);
            return;
        }
        if (!selSess) {
            selSess = new webim.Session(selType, selToID, selToID, "", Math.round(new Date().getTime() / 1000));
        }
        var isSend = true; //是否为自己发送
        var seq = -1; //消息序列，-1表示sdk自动生成，用于去重
        var random = Math.round(Math.random() * 4294967296); //消息随机数，用于去重
        var msgTime = Math.round(new Date().getTime() / 1000); //消息时间戳
        var subType; //消息子类型
        if (selType == webim.SESSION_TYPE.C2C) {
            subType = webim.C2C_MSG_SUB_TYPE.COMMON;
        } else {
            //webim.GROUP_MSG_SUB_TYPE.COMMON-普通消息,
            //webim.GROUP_MSG_SUB_TYPE.LOVEMSG-点赞消息，优先级最低
            //webim.GROUP_MSG_SUB_TYPE.TIP-提示消息(不支持发送，用于区分群消息子类型)，
            //webim.GROUP_MSG_SUB_TYPE.REDPACKET-红包消息，优先级最高
            subType = webim.GROUP_MSG_SUB_TYPE.COMMON;
        }
        var msg = new webim.Msg(selSess,
            isSend,
            seq,
            random,
            msgTime,
            loginInfo.identifier,
            subType,
            loginInfo.identifierNick);

        var text_obj, face_obj, tmsg, emotionIndex, emotion, restMsgIndex;
        //解析文本和表情
        var expr = /\[[^[\]]{1,3}\]/mg;
        var emotions = msgtosend.match(expr);
        if (!emotions || emotions.length < 1) {
            text_obj = new webim.Msg.Elem.Text(msgtosend);
            msg.addText(text_obj);
        } else {

            for (var i = 0; i < emotions.length; i++) {
                tmsg = msgtosend.substring(0, msgtosend.indexOf(emotions[i]));
                if (tmsg) {
                    text_obj = new webim.Msg.Elem.Text(tmsg);
                    msg.addText(text_obj);
                }
                emotionIndex = webim.EmotionDataIndexs[emotions[i]];
                emotion = webim.Emotions[emotionIndex];

                if (emotion) {
                    face_obj = new webim.Msg.Elem.Face(emotionIndex, emotions[i]);
                    msg.addFace(face_obj);
                } else {
                    text_obj = new webim.Msg.Elem.Text(emotions[i]);
                    msg.addText(text_obj);
                }
                restMsgIndex = msgtosend.indexOf(emotions[i]) + emotions[i].length;
                msgtosend = msgtosend.substring(restMsgIndex);
            }
            if (msgtosend) {
                text_obj = new webim.Msg.Elem.Text(msgtosend);
                msg.addText(text_obj);
            }
        }

        webim.sendMsg(msg,
            function(resp) {
                if (selType == webim.SESSION_TYPE.C2C) { //私聊时，在聊天窗口手动添加一条发的消息，群聊时，长轮询接口会返回自己发的消息
                    addMsg(msg);
                }
                webim.Tool.setCookie("tmpmsg_" + selToID, '', 0);
                $(".msgedit").val('');
                //turnoffFaces_box();
            },
            function(err) {
                alert(err.ErrorInfo);
                $(".msgedit").val('');
            });
    }

    function onKickedEventCall() {
        alert("您的账号在其他终端登录了,如有需要,请重新登录");
    }

    $(function() {
        webim.login(
            loginInfo,
            listeners,
            { isLogOn: true },
            function(resp) {
                loginInfo.identifierNick = resp.identifierNick; //设置当前用户昵称
                loginInfo.headurl = resp.headurl; //设置当前用户头像
                //initDemoApp();
            },
            function(err) {
                alert(err.ErrorInfo);
            }
        );

        $(".send").click(function() {
            onSendMsg();
        });


    });

    function addMsg(msg) {
        var isSelfSend, fromAccount, fromAccountNick, sessType, subType;

        fromAccount = msg.getFromAccount();
        if (!fromAccount) {
            fromAccount = '';
        }
        fromAccountNick = msg.getFromAccountNick();
        if (!fromAccountNick) {
            fromAccountNick = fromAccount;
        }
        isSelfSend = msg.getIsSend(); //消息是否为自己发的

        var onemsg = document.createElement("li");
        onemsg.className = "onemsg";
        var msghead = document.createElement("div");
        var msgbody = document.createElement("div");
        msghead.className = "labiim-chat-user";
        msgbody.className = "labiim-chat-text";
        //如果是发给自己的消息
        if (!isSelfSend) {

            msghead.style.color = "blue";
        } else {
            onemsg.className = onemsg.className + " labiim-chat-mine";
        }

        $(msghead).html("<img src=\"/content/images/head.png\" />");

        //昵称  消息时间
        //msghead.innerHTML = fromAccountNick + "&nbsp;&nbsp;" + webim.Tool.formatTimeStamp(msg.getTime());


        //解析消息
        //获取会话类型，目前只支持群聊
        //webim.SESSION_TYPE.GROUP-群聊，
        //webim.SESSION_TYPE.C2C-私聊，
        sessType = msg.getSession().type();
        //获取消息子类型
        //会话类型为群聊时，子类型为：webim.GROUP_MSG_SUB_TYPE
        //会话类型为私聊时，子类型为：webim.C2C_MSG_SUB_TYPE
        subType = msg.getSubType();


        switch (subType) {
        case webim.GROUP_MSG_SUB_TYPE.COMMON: //群普通消息
            $(msgbody).html(convertMsgtoHtml(msg));
            break;
            //case webim.GROUP_MSG_SUB_TYPE.REDPACKET://群红包消息
            //    msgPre.innerHTML = "[群红包消息]" + convertMsgtoHtml(msg);
            //    break;
            //case webim.GROUP_MSG_SUB_TYPE.LOVEMSG://群点赞消息
            //    //业务自己可以增加逻辑，比如展示点赞动画效果
            //    msgPre.innerHTML = "[群点赞消息]" + convertMsgtoHtml(msg);
            //    //展示点赞动画
            //    //showLoveMsgAnimation();
            //    break;
            //case webim.GROUP_MSG_SUB_TYPE.TIP://群提示消息
            //    msgPre.innerHTML = "[群提示消息]" + convertMsgtoHtml(msg);
            //    break;
        }

        //msgbody.appendChild(msgPre);

        onemsg.appendChild(msghead);
        onemsg.appendChild(msgbody);

        $(".labiim-chat-main ul").append(onemsg);
        //消息列表
        //var msgflow = document.getElementsByClassName("msgflow")[0];
        //msgflow.appendChild(onemsg);
        ////300ms后,等待图片加载完，滚动条自动滚动到底部
        //setTimeout(function () {
        //    msgflow.scrollTop = msgflow.scrollHeight;
        //}, 300);

    }

    function convertMsgtoHtml(msg) {
        var html = "", elems, elem, type, content;
        elems = msg.getElems(); //获取消息包含的元素数组
        for (var i in elems) {
            elem = elems[i];
            type = elem.getType(); //获取元素类型
            content = elem.getContent(); //获取元素对象
            switch (type) {
            case webim.MSG_ELEMENT_TYPE.TEXT:
                html += convertTextMsgToHtml(content);
                break;
            case webim.MSG_ELEMENT_TYPE.FACE:
                html += convertFaceMsgToHtml(content);
                break;
            case webim.MSG_ELEMENT_TYPE.IMAGE:
                html += convertImageMsgToHtml(content);
                break;
            case webim.MSG_ELEMENT_TYPE.SOUND:
                html += convertSoundMsgToHtml(content);
                break;
            case webim.MSG_ELEMENT_TYPE.FILE:
                html += convertFileMsgToHtml(content);
                break;
            case webim.MSG_ELEMENT_TYPE.LOCATION: //暂不支持地理位置
                //html += convertLocationMsgToHtml(content);
                break;
            case webim.MSG_ELEMENT_TYPE.CUSTOM:
                html += convertCustomMsgToHtml(content);
                break;
            case webim.MSG_ELEMENT_TYPE.GROUP_TIP:
                html += convertGroupTipMsgToHtml(content);
                break;
            default:
                webim.Log.error('未知消息元素类型: elemType=' + type);
                break;
            }
        }
        return html;
    }

    function convertTextMsgToHtml(content) {
        return content.getText();
    }

    //解析表情消息元素
    function convertFaceMsgToHtml(content) {
        var index = content.getIndex();
        var data = content.getData();
        var url = null;
        var emotion = webim.Emotions[index];
        if (emotion && emotion[1]) {
            url = emotion[1];
        }
        if (url) {
            return "<img src='" + url + "'/>";
        } else {
            return data;
        }
    }

    //解析图片消息元素
    function convertImageMsgToHtml(content) {
        var smallImage = content.getImage(webim.IMAGE_TYPE.SMALL); //小图
        var bigImage = content.getImage(webim.IMAGE_TYPE.LARGE); //大图
        var oriImage = content.getImage(webim.IMAGE_TYPE.ORIGIN); //原图
        if (!bigImage) {
            bigImage = smallImage;
        }
        if (!oriImage) {
            oriImage = smallImage;
        }
        return "<img src='" +
            smallImage.getUrl() +
            "#" +
            bigImage.getUrl() +
            "#" +
            oriImage.getUrl() +
            "' style='CURSOR: hand' id='" +
            content.getImageId() +
            "' bigImgUrl='" +
            bigImage.getUrl() +
            "' onclick='imageClick(this)' />";
    }

    //上传图片
    function uploadPic() {
        var uploadFiles = document.getElementById('upd_pic');
        var file = uploadFiles.files[0];
        var businessType; //业务类型，1-发群图片，2-向好友发图片
        if (selType == webim.SESSION_TYPE.C2C) { //向好友发图片
            businessType = webim.UploadPicBussinessType.C2C_MSG;
        } else if (selType == webim.SessionType.GROUP) { //发群图片
            businessType = webim.UploadPicBussinessType.GROUP_MSG;
        }
        //封装上传图片请求
        var opt = {
            'file': file, //图片对象
            'onProgressCallBack': onProgressCallBack, //上传图片进度条回调函数
            //'abortButton': document.getElementById('upd_abort'), //停止上传图片按钮
            'From_Account': loginInfo.identifier, //发送者帐号
            'To_Account': selToID, //接收者
            'businessType': businessType //业务类型
        };
        //上传图片
        webim.uploadPic(opt,
            function(resp) {
                //上传成功发送图片
                sendPic(resp);
                $('#upload_pic_dialog').modal('hide');
            },
            function(err) {
                alert(err.ErrorInfo);
            }
        );
    }

    //发送图片
    function sendPic(images) {
        if (!selToID) {
            alert("您还没有好友，暂不能聊天");
            return;
        }
        if (!selSess) {
            selSess = new webim.Session(selType,
                selToID,
                selToID,
                "",
                Math.round(new Date().getTime() / 1000));
        }
        var msg = new webim.Msg(selSess, true);
        var images_obj = new webim.Msg.Elem.Images(images.File_UUID);
        for (var i in images.URL_INFO) {
            var img = images.URL_INFO[i];
            var newImg;
            var type;
            switch (img.PIC_TYPE) {
            case 1: //原图
                type = 1; //原图
                break;
            case 2: //小图（缩略图）
                type = 3; //小图
                break;
            case 4: //大图
                type = 2; //大图
                break;
            }
            newImg = new webim.Msg.Elem.Images.Image(type,
                img.PIC_Size,
                img.PIC_Width,
                img.PIC_Height,
                img.DownUrl);
            images_obj.addImage(newImg);
        }
        msg.addImage(images_obj);
        //调用发送图片接口
        webim.sendMsg(msg,
            function(resp) {
                addMsg(msg);
                //curMsgCount++;
            },
            function(err) {
                alert(err.ErrorInfo);
            });
    }
</script>
</html>